package com.jswlw.controller.api;

import com.jswlw.common.BaseApiResponse;
import com.jswlw.common.ResponseStatus;
import com.jswlw.common.utils.DateUtils;
import com.jswlw.common.utils.XmlUtils;
import com.jswlw.common.wx.WeiXinHelper;
import com.jswlw.common.wx.WeiXinUserInfo;
import com.jswlw.common.wx.WxPayHelper;
import com.jswlw.common.wx.WxTokenResult;
import com.jswlw.controller.api.helper.UserHelper;
import com.jswlw.controller.api.req.wx.WxPayRequest;
import com.jswlw.controller.api.resp.UnifiedOrderResponse;
import com.jswlw.controller.api.resp.wx.Code2SessionResponse;
import com.jswlw.entity.biz.IdCreator;
import com.jswlw.service.biz.IdCreatorService;
import com.jswlw.service.biz.OrderInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.*;

import static com.jswlw.controller.BaseController.getIpAddr;

/**
 * @author 吴维斌 E-mail:wuweibin0817@163.com
 * @version 创建时间：${date} ${time}
 */
@Slf4j
@Api(tags = "微信管理")
@RestController
@RequestMapping("/api/wx")
public class WxApiController {

    @Autowired
    WxPayHelper wxPayHelper;
    @Autowired
    WeiXinHelper weiXinHelper;
    @Autowired
    UserHelper userHelper;
    @Autowired
    OrderInfoService orderInfoService;

    @ApiOperation(value = "获取微信token", notes = "获取微信token")
    @ApiResponse(code = 200, message = "OK", response = Code2SessionResponse.class)
    @GetMapping("code2Session/{code}")
    public Code2SessionResponse code2Session(@PathVariable("code") String code) {
        Code2SessionResponse response = new Code2SessionResponse();
        WxTokenResult wxTokenResult = weiXinHelper.getAccessToken(code);
        WeiXinUserInfo weiXinUserInfo = weiXinHelper.getWeiXinUserInfo(wxTokenResult.getAccess_token(), wxTokenResult.getOpenid());
        userHelper.createUser(weiXinUserInfo);
        response.setData(weiXinUserInfo);
        response.setCode(ResponseStatus.SUCCESS.getCode());
        response.setMsg("调用成功");
        return response;
    }

    @ApiOperation(value = "微信统一下单", notes = "微信统一下单")
    @ApiResponse(code = 200, message = "OK", response = UnifiedOrderResponse.class)
    @RequestMapping(value = "/unifiedorder", method = RequestMethod.POST)
    public UnifiedOrderResponse unifiedorder(@RequestBody WxPayRequest request, HttpServletRequest httpServletRequest) {
        return wxPayHelper.unifiedorder(request, getIpAddr(httpServletRequest));
    }

    @ApiOperation(value = "微信支付回调参数", notes = "微信支付回调参数")
    @ApiResponse(code = 200, message = "OK", response = BaseApiResponse.class)
    @RequestMapping(value = "/notifyPay", method = RequestMethod.POST)
    public String notifyPay(HttpServletRequest request) {
        //支付通知
        try {
            InputStream inStream = request.getInputStream();
            ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outSteam.write(buffer, 0, len);
            }
            String resultXml = new String(outSteam.toByteArray(), "utf-8");
            Map<String, String> params = XmlUtils.readStringXmlOut(resultXml);
            outSteam.close();
            inStream.close();
            log.info("===============付款成功==============");
            String total_fee = params.get("total_fee");
            double v = Double.valueOf(total_fee) / 100;
            String out_trade_no = String.valueOf(Long.parseLong(params.get("out_trade_no").split("O")[0]));
            String tradeNo = params.get("transaction_id");

            //支付处理订单
            orderInfoService.checkOrderAndUpdate(out_trade_no, Integer.valueOf(total_fee), tradeNo);


            return "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[返回结果错误]]></return_msg></xml>";
        } catch (Exception e) {
            log.error("支付回调信息错误", e);
        }
        return "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
    }

    @Autowired
    IdCreatorService idCreatorService;

    @ApiOperation(value = "createId", notes = "createId")
    @ApiResponse(code = 200, message = "OK", response = BaseApiResponse.class)
    @RequestMapping(value = "createId", method = RequestMethod.GET)
    public BaseApiResponse createId() {
        List<Integer> list = new ArrayList<>();
        for (int i = 100000; i < 1000000; i++) {
            list.add(i);
        }
        Collections.shuffle(list);
        Collections.shuffle(list);
        Collections.shuffle(list);
        Collections.shuffle(list);
        list.forEach(id -> {
            IdCreator idCreater = new IdCreator();
            idCreater.setId(id);
            System.out.println(id);
            idCreatorService.add(idCreater);
        });
        return BaseApiResponse.of().withResultSuccess();
    }
}
